package com.pat.web.controller;

import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.pat.web.ApiResponse;
import com.pat.web.model.NoteTags;

public class NoteTagsController extends Controller {

	public void getTags() {
		long noteId = getParaToLong("noteId");
		int view = getParaToInt("view");
		List<Record> records = Db.find(
				"select nt.id,nt.note_id noteId,nt.project_id projectId,nt.remark,nt.view,nt.hit,"
						+ "p.project_name projectName from note_tags nt join project p on nt.project_id = p.id "
						+ "where nt.note_id = ? and nt.view = ? order by nt.create_time desc,nt.hit desc limit 10",
				noteId, view);
		ApiResponse response = new ApiResponse();
		response.setData(records);
		response.setStatusCode("0000");
		renderJson(response);
	}

	public void getProjectTags() {
		long noteId = getParaToLong("noteId");
		long projectId = getParaToLong("projectId");
		List<Record> records = Db.find(
				"select remark from note_tags where note_id = ? and project_id = ? order by hit desc,create_time desc",
				noteId, projectId);
		Set<String> remarks = new LinkedHashSet<String>();
		if (records != null && records.size() > 0) {
			for (Record record : records) {
				String remark = record.getStr("remark");
				if (StringUtils.isNotBlank(remark)) {
					remarks.add(remark);
				}
			}
		}
		Record record = Db.findFirst("select remark from project where id = ?", projectId);
		if (record != null) {
			String remark = record.getStr("remark");
			if (remark != null) {
				String[] marks = remark.split("/");
				for (String mark : marks) {
					remarks.add(mark);
				}
			}
		}
		ApiResponse response = new ApiResponse();
		response.setData(remarks);
		response.setStatusCode("0000");
		renderJson(response);
	}

	public void addTag() {
		NoteTags tags = getBean(NoteTags.class, "");
		tags.setHit(1).setCreateTime(new Date()).save();
		ApiResponse response = new ApiResponse();
		response.setData(tags);
		response.setStatusCode("0000");
		renderJson(response);
	}

	public void delTag() {
		long tagId = getParaToLong("tagId");
		int del = Db.update("delete from note_tags where id = ?", tagId);
		ApiResponse response = new ApiResponse();
		response.setData(del);
		if (del > 0) {
			response.setStatusCode("0000");
		} else {
			response.setData("0003");
			response.setErrorMessage("删除失败，无该标签！");
		}
		renderJson(response);
	}
}
